package com.ifcreate.infowell.common.util;

import cn.hutool.core.bean.BeanUtil;
import com.ifcreate.infowell.common.exception.CustomException;
import org.apache.commons.lang.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author PuaChen
 * @Create 2018-09-18 17:37
 */
public class ObjectUtil {

    /**
     * 对象序列化为Map
     *
     * @param obj
     * @return
     */
    public static CustomMap convertObjectToMap(Object obj) {
        Map<String, Object> map = BeanUtil.beanToMap(obj);
        CustomMap customMap = CustomMap.create();
        customMap.putAll(map);
        return customMap;
    }

    /**
     * 将多个对象序列化为一个Map
     *
     * @param objs
     * @return
     */
    public static CustomMap convertObjectsToMap(Object... objs) {
        CustomMap data = CustomMap.create();
        for (Object obj : objs) {
            CustomMap map = convertObjectToMap(obj);
            data.putAll(map);
        }
        return data;
    }


    /**
     * 转换为  BigDecimal
     *
     * @param str
     * @return
     */
    public static BigDecimal convertBigDecimal(Object str) {
        return new BigDecimal(String.valueOf(str));
    }


    private static Pattern p = Pattern.compile("[0-9a-zA-Z]{1,}");

    /**
     * 是否是字母数字的组合
     *
     * @param s
     * @return
     */
    public static boolean isAlphaNumeric(String s) {
        Matcher m = p.matcher(s);
        return m.matches();
    }

    /**
     * 转换为  BigDecimal
     *
     * @param str
     * @return
     */
    public static BigDecimal convertBigDecimal(Object str, String defaultVal) {
        if (str == null || String.valueOf(str).isEmpty()) {
            str = defaultVal;
            if (StringUtils.isBlank(defaultVal)) {
                throw new CustomException("默认值不能为空");
            }
        }
        return new BigDecimal(String.valueOf(str));
    }

    public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>(1);
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }

    /**
     * 将字符串逗号分割 转化为数组
     *
     * @param str
     * @return
     */
    public static List<String> converStringForArray(String str) {
        ArrayList<String> array = new ArrayList<>();
        for (String s : str.split(",")) {
            if (StringUtils.isNotBlank(s)) {
                array.add(s);
            }
        }
        return array;
    }
}
